package com.sunchen.asc.service.parameter.server;

import com.sunchen.asc.service.common.ResultResponse;
import com.sunchen.asc.service.common.ResultUtil;
import com.sunchen.asc.service.parameter.api.ParamService;
import com.sunchen.asc.service.parameter.domain.Param;
import com.sunchen.asc.service.parameter.repository.ParamRepository;
import com.sunchen.asc.service.parameter.vo.ParamVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.List;

@DubboService(retries = 0)
public class ParamServiceImpl implements ParamService {


    @Autowired
    private ParamRepository paramRepository;

    public ResultResponse create(ParamVo paramVo) {

        Long countT = paramRepository.countByTitleAndDeleteFlag(paramVo.getTitle(),0);
        if (countT > 0){
            return ResultUtil.failed("名称重复");
        }
        Param param = new Param();
        param.setValue1(paramVo.getValue1());
        param.setValue2(paramVo.getValue2());
        param.setValueFlag(paramVo.getValueFlag());
        param.setFixed(paramVo.getFixed());
        param.setTitle(paramVo.getTitle());
        param.setDeleteFlag(0);
        param.setTypeId(paramVo.getTypeId());
        //param.setCreateUser();
        paramRepository.save(param);

        return ResultUtil.success("1");
    }

    public ResultResponse edit(ParamVo paramVo) {

        Param param = paramRepository.getOne(paramVo.getId());

        if (!param.getTitle().equals(paramVo.getTitle())){
            Long countT = paramRepository.countByTitleAndDeleteFlag(paramVo.getTitle(),0);
            if (countT > 0){
                return ResultUtil.failed("名称重复");
            }
        }
        param.setTitle(paramVo.getTitle());
        param.setValue1(paramVo.getValue1());
        param.setValue2(paramVo.getValue2());
        param.setValueFlag(paramVo.getValueFlag());
        //param.setUpdateUser();
        paramRepository.save(param);

        return ResultUtil.success("1");
    }

    public ResultResponse delete(Long id) {

        Param param = paramRepository.getOne(id);
        if (param.getFixed() == 1){
            return ResultUtil.failed("固定参数无法删除");
        }
        param.setDeleteFlag(1);
        param.setDeleteTime(new Timestamp(System.currentTimeMillis()));
        //param.setDeleteUser();
        paramRepository.save(param);
        return ResultUtil.success("1");
    }

    public ResultResponse get(Long typeId) {

        List<ParamVo> vos = paramRepository.findVoByTypeId(typeId);
        return ResultUtil.success(vos);
    }
}
